package com.yozinga.fragment;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.GatheringByteChannel;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yozinga.MerchantLocationMap;
import com.yozinga.OfferDealPageRating;
import com.yozinga.R;
import com.yozinga.facebook.FacebookConnector;
import com.yozinga.facebook.SessionEvents;
import com.yozinga.fragment.ShareDialogFragment.ShareListener;
import com.yozinga.model.BaseModel.OnRequestFinishedCallback;
import com.yozinga.model.RedeemOfferModel;
import com.yozinga.util.AlertDialogManager;
import com.yozinga.util.AlertDialogManager.AlertListener;
import com.yozinga.util.AppData;
import com.yozinga.util.NativeAppInvoker;
import com.yozinga.util.ToolKit;

public class OfferDealPageFragment extends BaseFragment implements AlertListener,OnClickListener,OnRequestFinishedCallback,ShareListener{

	Bitmap mDealLogoBitmap;
	ImageView ivDealImage;
	String mOfferId;
	RedeemOfferModel redeemOfferModel;
	Bundle bundle;
	String latitude;
	String longitude;
	String dealName,dealTageLine;
	TwitterShareListener mTwitterShareListener;

	//FaceBook
	private static final String FACEBOOK_APPID = "610748678957524";
	private static final String FACEBOOK_PERMISSION = "publish_stream";
	private static final String TAG = "FacebookSample";
	private final Handler mFacebookHandler = new Handler();
	private FacebookConnector facebookConnector;
	String couponText,imageNumber;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_offer_dealpage, container,false);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mTwitterShareListener = (TwitterShareListener)activity;
	}

	public interface TwitterShareListener{
		public void dealShare(String dealName,String dealTagLine);
	}


	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		//Face Book
		this.facebookConnector = new FacebookConnector(FACEBOOK_APPID, getActivity(), getActivity(), new String[] {FACEBOOK_PERMISSION});


		//OFFER
		bundle = this.getArguments();
		latitude = bundle.getString("latitude");
		longitude = bundle.getString("longitude");

		String dealLogo = bundle.getString("dealLogo");
		ImageDownLoad imageDownLoad = new ImageDownLoad();
		imageDownLoad.execute(dealLogo);
		mOfferId = bundle.getString("offerId");

		((TextView)getView().findViewById(R.id.tvPhoneNumber)).setText("+"+bundle.getString("merchantPhoneNumber"));
		((TextView)getView().findViewById(R.id.tvPhoneNumber)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				NativeAppInvoker nativeAppInvoker = new NativeAppInvoker(getActivity());
				nativeAppInvoker.dialPadInvoker(bundle.getString("merchantPhoneNumber"));
			}
		});
		ivDealImage = (ImageView)getView().findViewById(R.id.ivDealimage);

		dealName = bundle.getString("dealName");
		TextView tvDealName = (TextView) getView().findViewById(R.id.tvDealName);
		tvDealName.setText(dealName);

		dealTageLine = bundle.getString("offTagLine");
		TextView tvDealTagLine = (TextView) getView().findViewById(R.id.dealTagLine);
		tvDealTagLine.setText(dealTageLine);


		TextView tvDealDesc = (TextView) getView().findViewById(R.id.dealDesc);
		tvDealDesc.setText(bundle.getString("dealDesc"));


		TextView tvDealLimitations = (TextView) getView().findViewById(R.id.dealLimitations);
		tvDealLimitations.setText(bundle.getString("offLimitations"));

		TextView tvDealDates = (TextView) getView().findViewById(R.id.dealDates);
		tvDealDates.setText(bundle.getString("offerStart")+"to"+bundle.getString("offerEnd"));

		ImageView ivShare = (ImageView)getView().findViewById(R.id.ivShare);
		ivShare.setOnClickListener(this);

		ImageView ivRedeem = (ImageView)getView().findViewById(R.id.ivRedeem);
		ivRedeem.setOnClickListener(this);
		ivRedeem.setVisibility(View.VISIBLE);

		((TextView)getView().findViewById(R.id.tvMap)).setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {

		if(v.getId() == R.id.ivShare){
			ShareDialogFragment dialogFragment = new ShareDialogFragment(getActivity(),dealName,dealTageLine,this);
			dialogFragment.show(getFragmentManager(), "fragment_share_dealpage");
		}else if(v.getId() == R.id.ivRedeem){
			Intent intent = new Intent("com.laundrylocker.barcodescanner.SCAN");
			intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
			startActivityForResult(intent, 3);
		}else if(v.getId() ==  R.id.tvMap){
			Intent intent = new Intent(getActivity(),MerchantLocationMap.class);

			intent.putExtra("latitude", latitude);
			intent.putExtra("longitude", longitude);
			startActivity(intent);
		}
	}


	public class ImageDownLoad extends AsyncTask<String, Void, Bitmap>{

		@Override
		protected Bitmap doInBackground(String... params) {
			try {
				Log.e("src",params[0]);
				URL url = new URL(params[0]);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.setDoInput(true);
				connection.connect();
				InputStream input = connection.getInputStream();
				Bitmap myBitmap = BitmapFactory.decodeStream(input);
				Log.e("Bitmap","returned");
				return myBitmap;
			} catch (IOException e) {
				e.printStackTrace();
				Log.e("Exception",e.getMessage());
				return null;
			}

		}
		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			ivDealImage.setImageBitmap(result);
		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.i("Today","onActivityResult : requestCode"+requestCode);
		if (requestCode == 3) {
			Log.i("Today","onActivityResult : requestCode if"+Activity.RESULT_OK);
			//if (resultCode != Activity.RESULT_OK) {
			//String format = data.getStringExtra("SelectedBook");
			//String RedeemCode1 = data.getStringExtra("SCAN_RESULT");
			//String format = data.getStringExtra("SCAN_RESULT_FORMAT");
			String RedeemCode = /*data.getStringExtra("SelectedBook");*/"bea49f73-9772-4eb1-8df8-26960a001ade";
			//Log.i("Today","Redeem Code is:"+RedeemCode+"format"+format+"RedeemCode1"+RedeemCode1);

			//08-15 15:28:43.276: I/Today(21341): Redeem Code is:85579e5f-df34-42a7-a550-168da8599199

			String offerId = mOfferId;
			Log.i("Today","OfferId is:"+offerId);

			if(RedeemCode!=null){
				AlertDialogManager alertDialogManager = new AlertDialogManager();
				alertDialogManager.showAlertDialog2(getActivity(), null,offerId,RedeemCode, true, "Redeem","Cancel",this);
			}
			

			//} 
		}else{
			this.facebookConnector.getFacebook().authorizeCallback(requestCode, resultCode, data);
		}
	}

	@Override
	public void onRequestFinished(int resultCode, Bundle payload) {
		if(payload.get("action").equals("com.yozinga.redeemoffer")){
			Toast.makeText(getActivity(), "Your offer is Redeemed", Toast.LENGTH_LONG).show();
			String response = payload.getString("ServiceResponse");
			Log.i("Today","RedeemOffer Respons is :"+payload.getString("ServiceResponse"));
			ToolKit.stopprogess();
			Intent ratingIntent = new Intent(getActivity(),OfferDealPageRating.class);
			ratingIntent.putExtra("offerId",mOfferId);
			startActivity(ratingIntent);
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		if(redeemOfferModel!=null)
			redeemOfferModel.removeOnServiceRequestCompleteListener(this);
	}




	//Face Book
	public void postMessage() {

		if (facebookConnector.getFacebook().isSessionValid()) {
			postMessageInThread();
		} else {
			SessionEvents.AuthListener listener = new SessionEvents.AuthListener() {

				public void onAuthSucceed() {
					postMessageInThread();
				}


				public void onAuthFail(String error) {

				}
			};
			SessionEvents.addAuthListener(listener);
			facebookConnector.login();
		}
	}

	private void postMessageInThread() {
		Thread t = new Thread() {
			public void run() {

				try {
					facebookConnector.postMessageOnWall(getFacebookMsg());
					mFacebookHandler.post(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(getActivity(), "FaceBook Updated", Toast.LENGTH_LONG).show();
							Log.i("Today","FaceBook Updated");
						}
					});
				} catch (Exception ex) {
					Log.e(TAG, "Error sending msg",ex);
				}
			}
		};
		t.start();
	}

	private String getFacebookMsg() {
		return  dealName+"\n"+dealTageLine;
	}

	@Override
	public void faceBookShare() {
		postMessage();
	}

	@Override
	public void twitterShare() {
		mTwitterShareListener.dealShare(dealName, dealTageLine);
	}

	@Override
	public void positiveClicked(String offerId,String redeemCode) {

		ToolKit.startProgress(getActivity(), R.string.loading);
		redeemOfferModel = new RedeemOfferModel(getActivity());
		redeemOfferModel.addOnServiceRequestCompletedListener(this);
		
		String deviceId = Settings.Secure.getString(getActivity().getContentResolver(), 
				Settings.Secure.ANDROID_ID);
		Log.i("Today","Device ID is: "+deviceId);

		redeemOfferModel.redeemOffer(AppData.REDEEM_OFFER, offerId, deviceId, redeemCode);
	}

	@Override
	public void negativeClicked() {

	}
}
